package org.bing.balancer.impl.netty;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

public class HttpNettyNioServer {
    private static final int PROCESSOR_NUM = Runtime.getRuntime().availableProcessors();
    private NioServerSocketChannelFactory factory;
    private int port;

    public HttpNettyNioServer(int port) {
        this(port, 1, PROCESSOR_NUM > 4 ? PROCESSOR_NUM : PROCESSOR_NUM * 2);
    }

    public HttpNettyNioServer(int port, int bossThreadNum, int workThreadNum) {
        ExecutorService boss = Executors.newFixedThreadPool(1);
        ExecutorService work = Executors.newFixedThreadPool(workThreadNum);
        factory = new NioServerSocketChannelFactory(boss, work);
        this.port = port;
    }

    public void start() {
        ServerBootstrap bootstrap = new ServerBootstrap(factory);
        bootstrap.setPipelineFactory(new HttpPipelineFactory());
        bootstrap.bind(new InetSocketAddress(port));
    }

    public static void main(String[] args) {
        HttpNettyNioServer server = new HttpNettyNioServer(8080);
        server.start();
    }
}
